
var prefix = ctx +"module/device/node";
var formSelects = null
$(function() {
    load();
    getTemperatureRecordData(0);

    setInterval(function(){
        reLoad(); // 重载当前页面
        getTemperatureRecordData(0);
    },120000); // 参数为刷新间隔（单位为毫秒），这里表示每1分钟刷新一次
});
function load(){
    layui.use(['form','table', 'laydate'], function() {
        var form = layui.form , table = layui.table,element = layui.element,laydate = layui.laydate,layformSelects = layui.formSelects;//载入table模块
        formSelects = layformSelects;
        laydate.render({
            elem: '#search_date',
            isInitValue: false,
            done:function (value, data) {
                getTemperatureRecordData(0)
            }
        });

        // form.on('select(feedId0)', function (data) {
            // getTemperatureRecordData(0)
        // });
        var searchParams = {};
        searchParams['search_like_keyword']=$('#keyword').val();
        searchParams['search_eq_deviceId']=$('#deviceId').val();
        searchParams['search_eq_shopId']=$('#shopId').val();
        if ($('#positionType').val() && $('#positionType').val() != 0){
            searchParams['search_eq_positionType']=$('#positionType').val();
        }
        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            toolbar: '#toolbarDemo',
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            // height: 'full-75',
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            defaultToolbar: false,
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            cols: [[
                {type:'numbers',title: '序号', width:'5%'},
                { field : 'deviceNum',  title : '设备编号', align : 'center', },
                { field : 'terminalName',  title : '设备名称', align : 'center', },
                { field : 'deviceType',  title : '设备类型', align : 'center',
                    templet: function (item) {
                        if (item.deviceType == 2) {
                            return '<span class="label label-success">超高温设备</span>';
                        } else  if (item.deviceType == 3){
                            return '<span class="label label-danger ">电流设备</span>';
                        } else  if (item.deviceType == 4){
                            return '<span class="label label-danger ">测重量设备</span>';
                        } else  if (item.deviceType == 5){
                            return '<span class="label label-danger ">雷达测距设备</span>';
                        } else if (item.deviceType == 6){
                            return '<span class="label label-danger ">测电压设备</span>';
                        } else{
                            return '<span class="label label-danger ">未知类型</span>';
                        }
                    },
                },
                { field : 'nodeIndex',  title : '设备节点', align : 'center', },
                { field : 'insIndex',  title : 'INS索引', align : 'center', },
                { field : 'currentValue',  title : '当前值', align : 'center',
                    templet: function (item) {
                        if (item.deviceType == 2) {
                            return '<span class="label label-success" style="font-size:30px;">' + item.currentValue + '℃</span>';
                        } else if (item.deviceType == 4) {
                            return '<span class="label label-success" style="font-size:30px;">' + item.currentValue + 'KG</span>';
                        }
                        else{
                            return '<span class="label label-success" style="font-size:30px;">' + item.currentValue + '</span>';
                        }

                    },
                },
                { title: '操作', minWidth: 100, templet: '#currentTableBar', fixed: "right", align: "center"}
            ]],
            id: 'currentTableId'//表格Id
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id)
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id)
                remove(obj.data.id);
            } else if (obj.event === 'charts') {  // 监听删除操作
                console.log('obj',obj.data.id);
                goCharts(obj.data.id);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                add();
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
        });
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_like_keyword']=$('#keyword').val();
    searchParams['search_eq_deviceId']=$('#deviceId').val();
    searchParams['search_eq_shopId']=$('#shopId').val();
    searchParams['search_eq_positionType']=$('#positionType').val();
    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
        console.log('page',page)
        table.reload('currentTableId', {
            page: {curr: page}
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}
function searchFeedData(index) {
    console.log("searchFeedData", index)
    console.log("nodeId0", $("#nodeId0").val())
    console.log("nodeId1", $("#nodeId1").val())
    console.log("nodeId2", $("#nodeId2").val())
    console.log("nodeId3", $("#nodeId3").val())
    console.log("nodeId4", $("#nodeId4").val())
    console.log("nodeId5", $("#nodeId5").val())
    console.log("nodeId6", $("#nodeId6").val())
    console.log("nodeId7", $("#nodeId7").val())

    console.log("select0", formSelects.value('select0', 'valStr'))
    console.log("select1", formSelects.value('select1', 'valStr'))
    console.log("select2", formSelects.value('select2', 'valStr'))
    console.log("select3", formSelects.value('select3', 'valStr'))
    console.log("select4", formSelects.value('select4', 'valStr'))
    console.log("select5", formSelects.value('select5', 'valStr'))
    console.log("select6", formSelects.value('select6', 'valStr'))
    getTemperatureRecordData(0)
}

function changeFeedData(index) {
    console.log("changeFeedData", index)
    console.log("nodeId" + index, $("#nodeId"+ index).val())
    console.log("cfeedId"+ index, $("#cfeedId"+ index).val())
    $.ajax({
        cache : true,
        type : "POST",
        url : ctx + "module/feed/changeFeed",
        data:{
            nodeId: $("#nodeId"+ index).val(),
            feedId: $("#cfeedId"+ index).val(),
        },
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            console.log('data',data);
            if (data.code == 0){
                layer.msg("切换成功");
            }else {
                layer.msg("切换失败")

            }

        }
    });
}


/**
 * 获取设备的统计
 */
function getTemperatureRecordData(type) {
    var nodeIds = "";
    var feedIds = "";
    try{
        for (var i = 0; i < 7; i++){
            if (formSelects.value('select' + i, 'valStr')){
                if (nodeIds == ""){
                    nodeIds = $("#nodeId"+i).val()
                }else {
                    nodeIds = nodeIds + "-" + $("#nodeId"+i).val()
                }
                if (feedIds == ""){
                    feedIds = formSelects.value('select' + i, 'valStr')
                }else {
                    feedIds = feedIds + "-" + formSelects.value('select' + i, 'valStr')
                }
            }
        }

    }catch (e) {

    }
    console.log('$(\'#deviceId\').val()',$('#deviceId').val());
    var url = ctx + "module/device/node/charts/dataNew";
    $.ajax({
        cache : true,
        type : "POST",
        url : url,
        data:{
            deviceId: $('#deviceId').val(),
            shopId: $('#shopId').val(),
            positionType: $('#positionType').val(),
            deviceShowType: $('#deviceShowType').val(),
            dateType: type,
            feedId: $('#feedId').val(),
            searchDate: $('#search_date').val(),
            nodeIds: nodeIds,
            feedIds: feedIds
        },
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            console.log('data',data);
            let all_data_2 = data.all_data_2;
            let all_data_3 = data.all_data_3;

            if(all_data_2.dataList != undefined && all_data_2.dataList.length > 0){
                reloadTempData2(all_data_2);
            }
            // else{
            //     $("#divTemp").css("display", "none");
            // }

            console.log('all_data_3',all_data_3)
            console.log('all_data_3.length',all_data_3.length)
            if(all_data_3.dataList != undefined && all_data_3.dataList.length > 0){
                reloadDianLiuData(all_data_3);
            }else{
                $("#divDianliu").css("display", "none");
            }
        }
    });
}


function exportData() {
    layer.confirm('确定要导出吗？数量多导出时间会很长【导出时请耐心等待，不要刷新界面！】', {
        btn : [ '确定', '取消' ]
    }, function() {
        var deviceId = $('#deviceId').val()
        var shopId = $('#shopId').val()
        var positionType = $('#positionType').val()
        var deviceShowType = $('#deviceShowType').val()
        var dateType = 0
        var feedId = $('#feedId').val()
        var searchDate = $('#search_date').val()

        window.location.href = ctx + 'module/device/node/exportNodeData?deviceId=' + deviceId +'&shopId=' +  shopId
            +'&positionType=' +  positionType + '&deviceShowType=' +  deviceShowType + '&dateType=' +  dateType +
            '&feedId=' +  feedId + '&searchDate=' +  searchDate;

        layer.closeAll();
    })
}


function reloadTempData(data){

    var times = data.dataList[0].times;

    var legend = data.deviceNames;

    var series = [];
    for (let index in data.dataList){
        var values = data.dataList[index].values;
        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        let serie = {
            type:'line',
            name: legend[index],
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);
    }


    var lineChart = echarts.init(document.getElementById("echarts-line-chart-wendu"));
    var lineoption = {
        tooltip : {
            trigger: 'axis',
            show : true
        },
        legend: {
            data: legend
        },
        grid:{
            x:30,y:30,x2:5
        },
        calculable : true,
        xAxis : {
            type: 'category',
            data: times,
            boundaryGap: false,
        },
        yAxis : [
            {
                type : 'value',
                max:100,
                axisLabel : {
                    formatter: '{value}'
                }
            }
        ],
        series : series,
    };
    lineChart.setOption(lineoption);
    $(window).resize(lineChart.resize);
}

// 单个一条线
function reloadTempData2(data){
    for (let index in data.dataList){
        document.getElementById("divTemp"+index).style.display="";
        $("#"+ "nodeId"+index).val(data.dataList[index].nodeId)
        var times = data.dataList[index].times;

        var legendstr =  data.deviceNames[index]
        var legends =  []
        legends.push(data.deviceNames[index])
        var values = data.dataList[index].values;
        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        var series = [];
        let serie = {
            type:'line',
            name: legendstr,
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);

        var lineChart = echarts.init(document.getElementById("echarts-line-chart-wendu"+index));
        var lineoption = {
            tooltip : {
                trigger: 'axis',
                show : true,
                formatter: function (params) {
                    // params 是一个包含当前数据信息的数组
                    var result = params[0].name + '<br/>';
                    result += params[0].axisValue + '<br/>';
                    params.forEach(function (item) {
                        result += item.seriesName + ': ' + item.value + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: legends
            },
            grid:{
                x:30,y:30,x2:5
            },
            calculable : true,
            xAxis : {
                type: 'category',
                data: times,
                boundaryGap: false,
            },
            yAxis : [
                {
                    type : 'value',
                    max:100,
                    axisLabel : {
                        formatter: '{value}'
                    }
                }
            ],
            series : series,
        };
        lineChart.setOption(lineoption);
        $(window).resize(lineChart.resize);
    }
}


function reloadDianLiuData(data){

    var times = data.dataList[0].times;

    var legend = data.deviceNames;

    var series = [];
    for (let index in data.dataList){
        var values = data.dataList[index].values;

        for(let i in  values){
            let value = values[i];
            if(value == "" || value == "null"){
                values[i] = null;
            }
        }
        let serie = {
            type:'line',
            name: legend[index],
            data: values,
            smooth: true // 可选，使线条平滑
            // itemStyle: {
            //     normal: {
            //         label: {
            //             show: true, //开启显示
            //             position: 'top', //在上方显示
            //             textStyle: { //数值样式
            //                 color: 'blue',
            //                 fontSize: 16
            //             }
            //         }
            //     }
            // },
        };
        series.push(serie);
    }


    var lineChart = echarts.init(document.getElementById("echarts-line-chart-dianliu"));
    var lineoption = {
        tooltip : {
            trigger: 'axis',
            show : true
        },
        legend: {
            data: legend
        },
        grid:{
            x:30,y:30,x2:5
        },
        calculable : true,
        xAxis : {
            type: 'category',
            data: times,
        },
        yAxis : [
            {
                type : 'value',
                axisLabel : {
                    formatter: '{value}'
                }
            }
        ],
        series : series,
    };
    lineChart.setOption(lineoption);
    $(window).resize(lineChart.resize);
}



function add() {
    var deviceId = $("#deviceId").val();
    var shopId = $("#shopId").val();
    var deviceShowType = $("#deviceShowType").val();
    var url = prefix + '/add/' + deviceId;
    if(deviceShowType == 1){
        url = prefix + '/addByShop/' + shopId;
    }
	var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '600px' ],
        content : url // iframe的url
    });
	// layer.full(index);
}

function goCharts(id) {
    var index = layer.open({
        type : 2,
        title : '高温设备监控',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '350px' ],
        content : prefix + '/charts/' + id // iframe的url
    });
    layer.full(index);
}

function edit(id) {
	var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '600px' ],
        content : prefix + '/edit/' + id // iframe的url
    });
	// layer.full(index);
}

function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code===0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}


